package com.springboot.ww.sharding;

import cn.hutool.core.collection.CollUtil;
import com.google.common.collect.Range;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingValue;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Luobinbin
 * @date 2022/10/08 11:40
 */
@Slf4j
//@Component
public class PackageHisAlgorithm implements ComplexKeysShardingAlgorithm<Comparable<?>> {

    @Setter
    private Properties props = new Properties();

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, ComplexKeysShardingValue<Comparable<?>> complexKeysShardingValue) {
        //如果有id 则说明是插入数据 返回最新分片表即可 如果没有id说明是查询数据 返回旧表及新分片表
        // 获取表名
        String logicTable = complexKeysShardingValue.getLogicTableName();
        // 精确查询
        Map<String, Collection<Comparable<?>>> columnNameAndShardingValuesMap = complexKeysShardingValue.getColumnNameAndShardingValuesMap();
        if (CollUtil.isNotEmpty(columnNameAndShardingValuesMap)) {
            Collection<Comparable<?>> idCollection = columnNameAndShardingValuesMap.get("id");
            Collection<Comparable<?>> packageCodeCollection = columnNameAndShardingValuesMap.get("package_code");
            //新增
            if (idCollection != null && packageCodeCollection != null) {
                List<String> packageCodeList = packageCodeCollection.stream().map(o -> o.toString()).collect(Collectors.toList());
                return Arrays.asList(logicTable + "_" + packageCodeList.get(0).substring(2, 4));
            } else if (packageCodeCollection != null) {
                List<String> packageCodeList = packageCodeCollection.stream().map(o -> o.toString()).collect(Collectors.toList());
                String newTable = logicTable + "_" + packageCodeList.get(0).substring(2, 4);
                return Arrays.asList(newTable,logicTable);
            }else {
                return Arrays.asList(logicTable);
            }
        }
        //范围查询只返回老表
        Map<String, Range<Comparable<?>>> columnNameAndRangeValuesMap = complexKeysShardingValue.getColumnNameAndRangeValuesMap();
        if (CollUtil.isNotEmpty(columnNameAndRangeValuesMap)) {
            Range<Comparable<?>> range = columnNameAndRangeValuesMap.get("id");
            if (range != null) {
                return Arrays.asList(logicTable);
            }
        }
        return availableTargetNames;
    }

    @Override
    public Properties getProps() {
        return props;
    }

    @Override
    public void init(Properties properties) {

    }

    @Override
    public String getType() {
        return "packageHisAlgorithm";
    }
}
